//
//  NetworkStatusManager.swift
//  Wanke
//
//  Created by BO ZHOU on 2020/10/29.
//

import UIKit

open class NetworkStatusManager: NSObject {
    
    static let manager: NetworkStatusManager = NetworkStatusManager()
    
    private override init() {
        
    }

    /** `加载中...`view 的缓存数组 */
    var loadingViewArray: [NetWorkLoadingView] = []
    
    
    /** `网络报错`view的缓存数组 */
    var errorViewArray: [NetWorkErrorView] = []
    
    /** `无数据`view的缓存数组 */
    var nodataViewArray: [NodataView] = []
    
    
    /**
     * 获取一个加载中的view
     */
    class func getLoadingViewInstance() -> NetWorkLoadingView {
     
        manager.getLoadingViewInstance()
    }
    
    /**
     * 获取一个网络报错的view
     */
    class func getNetErrorView(buttonClickBlock: (()->Void)?) -> NetWorkErrorView {
        
        manager.getNetErrorView(buttonClickBlock: buttonClickBlock)
    }
    
    /**
     * 获取一个无数据view
     */
    class func getNodataView() -> NodataView {
        manager.getNodataView()
    }
    
    /**
     * 回收网络控件
     */
    class func cacheNetView(view: NetworkViewProtocol) {
        
        manager.cacheNetView(view: view)
    }
    
    
    
    /**
     * 获取一个加载中的view
     */
    private func getLoadingViewInstance() -> NetWorkLoadingView {
     
        if loadingViewArray.count > 0 {
            
            let view = loadingViewArray.first!
            loadingViewArray.removeFirst()
            return view
        }
        
        return NetWorkLoadingView()
    }
    
    /**
     * 获取一个网络报错的view
     */
    private func getNetErrorView(buttonClickBlock: (()->Void)?) -> NetWorkErrorView {
        
        var view: NetWorkErrorView! = nil
        
        if errorViewArray.count > 0 {
            view = errorViewArray.first!
            errorViewArray.removeFirst()
        } else {
            view = NetWorkErrorView()
        }
        
        view.buttonClickBlock = buttonClickBlock
        return view
    }
    
    
    /**
     * 获取一个无数据view
     */
    private func getNodataView() -> NodataView {
        var view: NodataView! = nil
        
        if nodataViewArray.count > 0 {
            view = nodataViewArray.first!
            nodataViewArray.removeFirst()
        } else {
            view = NodataView()
        }
        
        return view
    }
    
    /**
     * 回收网络控件
     */
    private func cacheNetView(view: NetworkViewProtocol) {
        
        if view is NetWorkErrorView {
            errorViewArray.append(view as! NetWorkErrorView)
        } else if view is NetWorkLoadingView {
            loadingViewArray.append(view as! NetWorkLoadingView)
            print("cache回收了loadingview")
        }
    }
}
